package com.junjie.blibli.service.impl;


import com.junjie.blibli.Entity.Files;
import com.junjie.blibli.dao.FileDao;
import com.junjie.blibli.service.FileService;
import com.junjie.blibli.util.FastDFSUtil;
import com.junjie.blibli.util.MD5Util;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.util.Date;

@Service
public class FileServiceImpl implements FileService{

    @Autowired
    private FileDao fileDao;

    @Autowired
    private FastDFSUtil fastDFSUtil;

    public String uploadFileBySlices(MultipartFile slice,
                                     String fileMD5,
                                     Integer sliceNo,
                                     Integer totalSliceNo) throws Exception {
        //根据md5唯一生成码查数据库，看是否之前存储过，存储过直接返回Url
        Files dbFilesMD5 = fileDao.getFileByMD5(fileMD5);
        if(dbFilesMD5 != null){
            return dbFilesMD5.getUrl();
        }
        //这里我们的url只有当最后一个分片被上传后，才会返回url，否则返回的是空字符串
        String url = fastDFSUtil.uploadFileBySlices(slice, fileMD5, sliceNo, totalSliceNo);
        //因此如果url不为空，就可以存到数据库中
        if(!StringUtil.isNullOrEmpty(url)){
            dbFilesMD5 = new Files();
            dbFilesMD5.setCreateTime(new Date());
            dbFilesMD5.setMd5(fileMD5);
            dbFilesMD5.setUrl(url);
            dbFilesMD5.setType(fastDFSUtil.getFileType(slice));
            fileDao.addFile(dbFilesMD5);
        }
        return url;
    }

    //获取文件的md5唯一标识
    @Override
    public String getFileMD5(MultipartFile file) throws Exception {
        return MD5Util.getFileMD5(file);
    }

    @Override
    public Files getFileByMD5(String fileMd5) {
        return fileDao.getFileByMD5(fileMd5);
    }
}
